const express = require("express");
const router = express.Router();
const crypto = require('crypto');
const pool = require("../pool.js");
const utils = require("../utils/index.js");
const EquityService = require('./online.js');
const { pushClearanceStatus } = require('./clearanceStatus.js');
const validCouponIds = ['114', '115', '116', '117'];

/**
 * 权益开通接口
 */
router.post('/order/receive', async (req, res) => {
  try {
    // 1. 验证签名
    const { contractRoot } = req.body;
    const { head, body } = contractRoot;
    console.log(1,head);
    console.log(2,body);
    // 签名验证逻辑
    const privateKey = 'FOCU8T7nWLftpvHW'; // 替换为实际密钥
    const signStr = head.transactionId + head.reqTime + privateKey + JSON.stringify(body);
    const expectedSign = crypto.createHash('md5').update(signStr).digest('hex').toUpperCase();
    
    // 不分大小写
    if (head.sign.toLowerCase() !== expectedSign.toLowerCase()) {
      return res.json({
        contractRoot: {
          head: {
            transactionId: head.transactionId,
            reqTime: new Date().toISOString(),
            sign: ''
          },
          body: {
            resultCode: '0002',
            resultMsg: '签名错误'
          }
        }
      });
    }
    
    // 2. 参数校验
    const requiredFields = ['orderItemId', 'rightsId', 'serverNum',  'quantity', 'skuId', 'skuCode', 'skuName', 'createTime'];
    for (const field of requiredFields) {
      if (!body[field]) {
        return res.json({
          contractRoot: {
            head: {
              transactionId: head.transactionId,
              reqTime: new Date().toISOString(),
              sign: ''
            },
            body: {
              resultCode: '0003',
              resultMsg: `缺少必要参数: ${field}`
            }
          }
        });
      }
    }
    let couponId=body.skuCode=='0415515649'? '114' : body.skuCode=='0415515795'?'115':body.skuCode=='0415515882'?'116':body.skuCode=='0415515914'?'117' :'';
    if(!validCouponIds.includes(couponId)){
      res.send({
                contractRoot:{
                  head:{},
                  body:{
                    msg_type:"paystatussyncresp",
                    version:"1.0",
                    status:"1",
                    message:"券类型错误"
                  },
                }
              });
    }else{
        let phone=body.serverNum;
        let accept_time=body.createTime;
        accept_time=accept_time.substring(0,4)+'-'+accept_time.substring(4,6)+'-'+accept_time.substring(6,8)+' '+accept_time.substring(8,10)+':'+accept_time.substring(10,12)+':'+accept_time.substring(12,14);
        let goodsJson=[];
        let vipType;
        if(couponId=='114'){
          vipType=1;
          goodsJson=[
            {
                productId:'114',
                iscoupon:0,
                skuName:"零食基础会员",
                imgUrl:"https://sx-manage.oss-cn-hangzhou.aliyuncs.com/images/20250802200859-%C3%A5%C2%9F%C2%BA%C3%A7%C2%A1%C2%80%C3%A4%C2%BC%C2%9A%C3%A5%C2%91%C2%98%402x%20(1).png",
                price:'25',
                orinprice:'1',
                inventory:'10000',
                buyNum:1,
            }
          ]
        }
        if(couponId=='115'){
          vipType=2;
          goodsJson=[
            {
                productId:'115',
                iscoupon:0,
                skuName:"零食精选会员",
                imgUrl:"https://sx-manage.oss-cn-hangzhou.aliyuncs.com/images/20250802200958-%C3%A5%C2%9F%C2%BA%C3%A7%C2%A1%C2%80%C3%A4%C2%BC%C2%9A%C3%A5%C2%91%C2%98%402x%20(2).png",
                price:'49',
                orinprice:'1',
                inventory:'10000',
                buyNum:1,
            }
          ]
        }
        if(couponId=='116'){
          vipType=3;
          goodsJson=[
            {
                productId:'116',
                iscoupon:0,
                skuName:"零食畅享会员",
                imgUrl:"https://sx-manage.oss-cn-hangzhou.aliyuncs.com/images/20250802201133-%C3%A5%C2%9F%C2%BA%C3%A7%C2%A1%C2%80%C3%A4%C2%BC%C2%9A%C3%A5%C2%91%C2%98%402x%20(3).png",
                price:'59',
                orinprice:'1',
                inventory:'10000',
                buyNum:1,
            }
          ]
        }
        if(couponId=='117'){
          vipType=4;
          goodsJson=[
            {
                productId:'117',
                iscoupon:0,
                skuName:"零食优选会员",
                imgUrl:"https://sx-manage.oss-cn-hangzhou.aliyuncs.com/images/20250802201206-%C3%A5%C2%9F%C2%BA%C3%A7%C2%A1%C2%80%C3%A4%C2%BC%C2%9A%C3%A5%C2%91%C2%98%402x%20(4).png",
                price:'69',
                orinprice:'1',
                inventory:'10000',
                buyNum:1,
            }
          ]
        }
        let order_no=utils.getOrderNo("yyyyMMddhhmmssS")+Math.floor(Math.random() * 89) + 10;
        let sql = "INSERT INTO t_new_order(order_id,phone,pay_time,total_price,total_discount,total_fee,coupon_id,goods_json,state,update_time,create_time,goodsIsOnlyCoupon,fromType) VALUES (?,?,?,?,?,?,?,?,?,now(),now(),?,'gxyd')";
          pool.query(sql, [order_no,phone,accept_time,goodsJson[0].orinprice,0,goodsJson[0].price,couponId,JSON.stringify(goodsJson),3,1], (err, result) => {
              if (err) return res.send(utils.returnData({code: -1,err,req}));
              let vipName;
                if(couponId=='114'){
                  vipType=1;
                  vipName="零食基础会员";
                }
                if(couponId=='115'){
                  vipType=2;
                  vipName="零食精选会员";
                }
                if(couponId=='116'){
                  vipType=3;
                  vipName="零食畅享会员";
                }
                if(couponId=='117'){
                  vipType=4;
                  vipName="零食优选会员";
                }
                //判断当前用户是否购买过同类型的会员，如果购买过，就更新会员到期时间，增加30天
                let sql = `SELECT * FROM user_vip WHERE phone = "${phone}" AND vip_type = "${vipType}"`;
                pool.query(sql, [],(err, result) => {
                    if (err) return res.send(utils.returnData({code: -1,err,req}));
                    if(result.length>0){
                      //更新会员到期时间，增加30天
                      let sql = `UPDATE user_vip SET vip_expiration_date = DATE_ADD(vip_expiration_date, INTERVAL 30 DAY) WHERE id = "${result[0].id}"`;
                      pool.query(sql, [],(err, result) => {
                        if (err) return res.send(utils.returnData({code: -1,err,req}));
                        res.send(utils.returnData({data: result}));
                      });
                    }else{
                      //新增会员
                      let sql = `INSERT INTO user_vip (phone, vip_type,vip_name, create_time,vip_expiration_date) VALUES ("${phone}", "${vipType}","${vipName}", NOW(),DATE_ADD(NOW(), INTERVAL 30 DAY))`;
                      pool.query(sql, [],(err, result) => {
                        if (err) return res.send(utils.returnData({code: -1,err,req}));
                        res.send(utils.returnData({data: result}));
                      });
                    }
                    utils.sedNewHttpMessageByVip(phone,vipName);
                    //不管是新增还是更新都要执行，会员送券方法
                    utils.sendCouponToUser(phone,vipType);
                    // 4. 返回成功响应
                    res.json({
                      contractRoot: {
                        head: {
                          transactionId: head.transactionId,
                          reqTime: new Date().toISOString(),
                          sign: crypto.createHash('md5')
                            .update(head.transactionId + new Date().toISOString() + privateKey + JSON.stringify({
                              resultCode: '1',
                              resultMsg: '成功',
                              recoId: order_no
                            }))
                            .digest('hex')
                            .toUpperCase()
                        },
                        body: {
                          resultCode: '1',
                          resultMsg: '成功',
                          recoId: order_no
                        }
                      }
                    });
                });
              
              //调用支付回调方法
                    // 使用示例
                    const orderExample = {
                      orderItemId: body.orderItemId,
                      rightsId:'12886126',
                      status:1,
                      msg:'开通成功',
                      coupon:couponId,
                      couponType:1,
                      createTime: new Date(new Date().getTime() + 10000).toLocaleDateString(), 
                    };
                    setTimeout(() => {
                      // 执行推送
                      const equityService = new EquityService();
                      equityService.pushEquityStatus(orderExample)
                      .then(response => console.log('全网推送成功:', response))
                      .catch(error => console.error('推送失败:', error));
                    }, 10000); 

                    setTimeout(() => {
                      pushClearanceStatus({
                        orderItemId: body.orderItemId,
                        serverNum: body.serverNum,
                        skuCode: body.skuCode,
                        skuName: goodsJson[0].skuName,
                        clearanceResult: 1, // 1-核销成功
                        couponId: couponId
                      });
                    },15000)

          });
        }
  } catch (error) {
    console.error('权益开通失败:', error);
    res.json({
      contractRoot: {
        head: {
          transactionId: req.body?.contractRoot?.head?.transactionId || '',
          reqTime: new Date().toISOString(),
          sign: ''
        },
        body: {
          resultCode: '9999',
          resultMsg: '系统异常'
        }
      }
    });
  }
});

//测试接口
 //测试
  router.get('/test', (req,res) => {
    const head = {
    apiId: '200047',
    channelCode: '202404080036',
    reqTime: '20250828111822718',
    sign: '376e0a84f2c1b1e6182dfa7cb611ee51',
    transactionId: '928f990b-062d-49c3-a49e-9efb3253f081828',
    version: '1.0'
    }
    const body = {
createTime: '20250828111823000',
extCode: '',
orderItemId: '1410584297195569153',
price: 0,
quantity: 1,
rightsId: '12886126',
serverNum: '15381465894',
skuCode: 'lyfv114',
skuId: '1234567890123458683',
skuName: '来伊份权益测试sku'
}

    const privateKey = 'FOCU8T7nWLftpvHW'; // 替换为实际密钥
    const signStr = head.transactionId + head.reqTime + privateKey + JSON.stringify(body);
    const expectedSign = crypto.createHash('md5').update(signStr).digest('hex').toUpperCase();
    console.log(1,expectedSign);
    //不分大小写
    if (head.sign.toLowerCase() !== expectedSign.toLowerCase()) {
      res.send({
        msg:'签名错误',
        data:{time:"",data:{}}
      })
    }else{
      res.send({
        msg:'测试专用',
        data:{time:"",data:{}}
      })
    }
  })




module.exports = router;
